package org.jeecg.modules.car.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.entity.car.CarDerateDetails;
import org.jeecg.entity.car.CarMerchantDerate;
import org.jeecg.enums.car.CarDerateStatusEnum;
import org.jeecg.enums.car.CarDerateTypeEnum;
import org.jeecg.modules.car.entity.CarMerchant;
import org.jeecg.modules.car.service.ICarDerateDetailsService;
import org.jeecg.modules.car.service.ICarMerchantDerateService;
import org.jeecg.modules.car.service.ICarMerchantService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.*;

/**
 * @Description: 优惠卷
 * @Author: shaopeng
 * @Date:   2020-10-25
 * @Version: V1.0
 */
@Slf4j
@Api(tags="优惠卷")
@RestController
@RequestMapping("/b/car/carMerchantDerate")
public class CarMerchantDerateController {
	@Autowired
	private ICarMerchantDerateService carMerchantDerateService;

	@Autowired
	private ICarDerateDetailsService carDerateDetailsService;

	@Autowired
	private ICarMerchantService carMerchantService;

	@Autowired
    private ISysUserRoleService sysUserRoleService;
	
	/**
	  * 分页列表查询
	 * @param carMerchantDerate
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "优惠卷-分页列表查询")
	@ApiOperation(value="优惠卷-分页列表查询", notes="优惠卷-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<CarMerchantDerate>> queryPageList(CarMerchantDerate carMerchantDerate,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		Result<IPage<CarMerchantDerate>> result = new Result<IPage<CarMerchantDerate>>();
		carMerchantDerate.setSqlMap(sysUserRoleService.dataScopeProjectOnlyFilter(SsoUtil.getLoginUser(),"p",carMerchantDerate.getMenuPath(),null,carMerchantDerate.getDepartIdEx()));
		Page<CarMerchantDerate> page = new Page<CarMerchantDerate>(pageNo, pageSize);
		page.setRecords(carMerchantDerateService.findPage(page,carMerchantDerate));
		result.setSuccess(true);
		result.setResult(page);
		return result;
	}



	@AutoLog(value = "优惠卷明细-分页列表查询")
	@ApiOperation(value="优惠卷明细-分页列表查询", notes="优惠卷明细-分页列表查询")
	@GetMapping(value = "/detailList")
	public Result<IPage<CarDerateDetails>> detailList(CarDerateDetails carDerateDetails,
														  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
														  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
														  HttpServletRequest req) {
		log.info("优惠卷明细查询参数：{}", carDerateDetails);
		Result<IPage<CarDerateDetails>> result = new Result<IPage<CarDerateDetails>>();
		carDerateDetails.setSqlMap(sysUserRoleService.dataScopeProjectOnlyFilter(SsoUtil.getLoginUser(),"p",carDerateDetails.getMenuPath(),null,carDerateDetails.getDepartIdEx()));
		Page<CarDerateDetails> page = new Page<CarDerateDetails>(pageNo, pageSize);
		page.setRecords(carDerateDetailsService.findDetailPage(page,carDerateDetails));
		result.setSuccess(true);
		result.setResult(page);
		return result;
	}


	
	/**
	  *   添加
	 * @param carMerchantDerate
	 * @return
	 */
	@AutoLog(value = "优惠卷-添加")
	@ApiOperation(value="优惠卷-添加", notes="优惠卷-添加")
	@PostMapping(value = "/add")
	public Result<CarMerchantDerate> add(@RequestBody CarMerchantDerate carMerchantDerate) {
		Result<CarMerchantDerate> result = new Result<CarMerchantDerate>();
		if (carMerchantDerate.getMerchantIdList().size() <= 0 || carMerchantDerate.getDerateNumber() <= 0){
			return result.error500("商家信息为空或优惠卷张数小于0无法添加");
		}
		//有效期校验
		if (carMerchantDerate.getStartTime().compareTo(carMerchantDerate.getEndTime()) >= 0) {
			return Result.error("优惠券的开始时间不能大于结束时间！");
		}
		Date now = new Date();
		if (carMerchantDerate.getEndTime().compareTo(now) <= 0) {
			return Result.error("优惠券结束时间不能小于当前时间！");
		}
		try {
			List<CarMerchantDerate> derateList = new ArrayList<>();
			CarMerchantDerate derate = null;
			//共选择商家多少商家，以及每个商家优惠卷的详细信息 * carMerchantDerate.getDerateNumber()
			for (int i = 0; i < carMerchantDerate.getMerchantIdList().size(); i++){
				//根据商户id获取商户信息
				CarMerchant merchant = carMerchantService.getById(carMerchantDerate.getMerchantIdList().get(i));
				for (int j = 0; j <carMerchantDerate.getDerateNumber(); j ++){
					derate = new CarMerchantDerate();
					derate.setTenantId(merchant.getTenantId());
					derate.setId(String.valueOf(IdWorker.getId()));
					derate.setDerateAmount(carMerchantDerate.getDerateAmount());
					derate.setProjectId(carMerchantDerate.getProjectId());
					derate.setMerchantId(carMerchantDerate.getMerchantIdList().get(i));
					derate.setDerateType(CarDerateTypeEnum.CAR_DERATE_TYPE_1.getCode());
					derate.setDerateMode(carMerchantDerate.getDerateMode());
					derate.setStatus(CarDerateStatusEnum.CAR_DERATE_STATUS_0.getCode());
					derate.setStartTime(carMerchantDerate.getStartTime());
					derate.setEndTime(carMerchantDerate.getEndTime());
					derate.setRemarks(carMerchantDerate.getRemarks());
					derateList.add(derate);
				}
			}
			carMerchantDerateService.saveBatch(derateList);
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}
	
	/**
	  *  编辑
	 * @param carMerchantDerate
	 * @return
	 */
	@AutoLog(value = "优惠卷-编辑")
	@ApiOperation(value="优惠卷-编辑", notes="优惠卷-编辑")
	@PutMapping(value = "/edit")
	public Result<CarMerchantDerate> edit(@RequestBody CarMerchantDerate carMerchantDerate) {
		Result<CarMerchantDerate> result = new Result<CarMerchantDerate>();
		CarMerchantDerate carMerchantDerateEntity = carMerchantDerateService.getById(carMerchantDerate.getId());
		//已失效,已使用的不可编辑
		if (CarDerateStatusEnum.CAR_DERATE_STATUS_2.getCode().equals(carMerchantDerateEntity.getStatus())
				|| CarDerateStatusEnum.CAR_DERATE_STATUS_MISS.getCode().equals(carMerchantDerateEntity.getStatus())) {
			return Result.error("已使用或已失效优惠券不可编辑！");
		}
		//有效期校验
		if (carMerchantDerate.getStartTime().compareTo(carMerchantDerate.getEndTime()) >= 0) {
			return Result.error("优惠券的开始时间不能大于结束时间！");
		}
		Date now = new Date();
		if (carMerchantDerate.getEndTime().compareTo(now) <= 0) {
			return Result.error("优惠券结束时间不能小于当前时间！");
		}
		if(carMerchantDerateEntity==null) {
			result.error500("优惠券系统中不存在！");
		}else {
			/*只允许编辑系统发放 && 状态为未使用的*/
			if (carMerchantDerate.getDerateType().equals(CarDerateTypeEnum.CAR_DERATE_TYPE_1.getCode()) &&
					carMerchantDerate.getStatus().equals(CarDerateStatusEnum.CAR_DERATE_STATUS_0.getCode())){
				//若为减免金额设置金额为0， 防止切换优惠劵规则后金额还在
				if (("2").equals(carMerchantDerate.getDerateMode()))
					carMerchantDerate.setDerateAmount(new BigDecimal(0));
				boolean ok =  carMerchantDerateService.updateById(carMerchantDerate);
				if(ok) {
					result.success("修改成功!");
				}
			}else{
				return Result.error("当前状态优惠券不允许操作");
			}
		}
		return result;
	}
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "优惠卷-通过id删除")
	@ApiOperation(value="优惠卷-通过id删除", notes="优惠卷-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		try {
			CarMerchantDerate carMerchantDerate = carMerchantDerateService.getById(id);
			if (carMerchantDerate == null){
				return Result.error("未查询到当前优惠券信息");
			}
			/*只允许删除系统发放 && 状态为未使用的*/
			if (carMerchantDerate.getDerateType().equals(CarDerateTypeEnum.CAR_DERATE_TYPE_1.getCode()) &&
			    carMerchantDerate.getStatus().equals(CarDerateStatusEnum.CAR_DERATE_STATUS_0.getCode())){
				return carMerchantDerateService.delDerate(null, carMerchantDerate.getId());
			}else{
				return Result.error("当前状态优惠券不允许操作");
			}
		} catch (Exception e) {
			log.error("删除失败",e.getMessage());
			return Result.error("删除失败!");
		}
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "优惠卷-批量删除")
	@ApiOperation(value="优惠卷-批量删除", notes="优惠卷-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<CarMerchantDerate> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<CarMerchantDerate> result = new Result<CarMerchantDerate>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}
		try {
			carMerchantDerateService.batchDelDerate(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}catch (Exception e){
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@AutoLog(value = "优惠卷-通过id查询")
	@ApiOperation(value="优惠卷-通过id查询", notes="优惠卷-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<CarMerchantDerate> queryById(@RequestParam(name="id",required=true) String id) {
		Result<CarMerchantDerate> result = new Result<CarMerchantDerate>();
		CarMerchantDerate carMerchantDerate = carMerchantDerateService.getById(id);
		if(carMerchantDerate==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(carMerchantDerate);
			result.setSuccess(true);
		}
		return result;
	}

  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
      // Step.1 组装查询条件
	  CarDerateDetails carDerateDetails = new CarDerateDetails();
      try {
          String paramsStr = request.getParameter("paramsStr");
          if (oConvertUtils.isNotEmpty(paramsStr)) {
              String deString = URLDecoder.decode(paramsStr, "UTF-8");
			  carDerateDetails = JSON.parseObject(deString, CarDerateDetails.class);
          }
      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      }
      LoginUser loginUser =  SsoUtil.getLoginUser();
      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      List<CarDerateDetails> pageList = carDerateDetailsService.findDetailPage(null,carDerateDetails);
//      List<CarMerchantDerate> pageList = carMerchantDerateService.list(queryWrapper);
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "优惠卷列表");
      mv.addObject(NormalExcelConstants.CLASS, CarDerateDetails.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("优惠卷列表数据", "导出人:" + loginUser.getRealname(), "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
  }

  /**
      * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<CarMerchantDerate> listCarMerchantDerates = ExcelImportUtil.importExcel(file.getInputStream(), CarMerchantDerate.class, params);
              carMerchantDerateService.saveBatch(listCarMerchantDerates);
              return Result.ok("文件导入成功！数据行数:" + listCarMerchantDerates.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
  }

}
